﻿using System;
using Localize;
using UnityEditor;

namespace UnityEngine.UI
{
    enum EditStatus
    {
        none,
        NewWord,
    }
    [CustomEditor(typeof(UIText), true)]
    public class LocalizedTextEditor : UnityEditor.UI.TextEditor
    {
        protected UIText mText;
        string[] allLangNames;
        string[] allKeys;
        string language;
        string text;
        string key;
        // EditStatus editStatus;
        protected override void OnEnable()
        {
            base.OnEnable();
            if (Application.isPlaying)
                return;
            if(i18n.Language==ELanguage.None)
                i18n.Language = ELanguage.CN;
            mText = target as UIText;
            i18n i = new i18n();
            allLangNames = i18n.AllLanguageNames;
            allKeys = i18n.AllKeys;
            language = i18n.Language.ToString();
            key = mText.mKey;
            text = mText.text;
            // editStatus = EditStatus.none;
        }
        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            if (Application.isPlaying)
                return;

            //语言
            var languageIdx = Array.IndexOf(allLangNames, language);
            var newlanguage = EditorGUILayout.Popup("Language", languageIdx, allLangNames);
            if (newlanguage != languageIdx)
            {
                language = allLangNames[newlanguage];
                i18n.Language = (ELanguage)Enum.Parse(typeof(ELanguage), language);
                //EditorUtility.SetDirty(target);
            }
            bool isKeyChange = false;
            bool isWordChange = false;
            //空文本
            if (string.IsNullOrEmpty(mText.text))
            {
                if (!string.IsNullOrEmpty(mText.mKey))
                {
                    mText.text = i18n._(mText.mKey, "");
                    text = mText.text;
                    key = mText.mKey;
                    EditorUtility.SetDirty(target);
                    return;
                }
            }
            if (string.IsNullOrEmpty(mText.mKey) && !string.IsNullOrEmpty(mText.text))
            {
                if (i18n.HasWord(mText.text))
                {
                    string k = i18n.GetWordKey(mText.text);
                    mText.mKey = k;
                    text = mText.text;
                    key = k;
                    EditorUtility.SetDirty(target);
                    return;
                }
            }
            //是否变了
            key = EditorGUILayout.TextField("key", key);
            if (key != null && key != mText.mKey)
            {
                if (i18n.HasKey(key))
                {
                    EditorGUILayout.LabelField("已经存在这个key , word = " + i18n._(key));
                    if (GUILayout.Button("使用"))
                    {
                        mText.mKey = key;
                        mText.text = i18n._(key, text);
                        text = mText.text;
                        EditorUtility.SetDirty(target);
                    }
                }
                else
                {
                    isKeyChange = true;
                }
            }
            string newtxt = mText.text;
            if (text != newtxt)
            {
                if (i18n.HasWord(newtxt))
                {
                    string k = i18n.GetWordKey(newtxt);
                    EditorGUILayout.LabelField("已经存在这个值 , key = " + k);
                    if (GUILayout.Button("使用"))
                    {
                        mText.mKey = k;
                        text = mText.text;
                        key = k;
                        EditorUtility.SetDirty(target);
                    }
                }
                else
                {
                    isWordChange = true;
                }
            }
            if (isKeyChange || isWordChange)
            {
                if (GUILayout.Button("保存"))
                {
                    mText.mKey = key;
                    mText.text = newtxt;
                    text = newtxt;
                    i18n.AddNewWord(key, newtxt);
                    EditorUtility.SetDirty(target);
                }
            }
            // else if (isKeyChange || isWordChange)
            // {
            //     if (isKeyChange)
            //     {
            //         EditorGUILayout.LabelField("请修改 Word");
            //     }
            //     if (isWordChange)
            //     {
            //         EditorGUILayout.LabelField("请修改 Key");
            //     }
            //     if (GUILayout.Button("取消"))
            //     {
            //         key = mText.mKey;
            //         mText.text = text;
            //         EditorUtility.SetDirty(target);
            //         updateFileName();
            //     }
            // }
        }

        [MenuItem("GameObject/UI/UIText")]
        static void CreateNewText()
        {
            GameObject go = new GameObject("UIText", typeof(UIText));
            var text = go.GetComponent<UIText>();
            text.raycastTarget = false;
            text.font = AssetDatabase.LoadAssetAtPath<Font>("Assets/Font/Custom-Bold.otf"); ;   // 默认字体
            go.transform.SetParent(Selection.activeTransform);
            RectTransform rectTran = go.transform as RectTransform;
            rectTran.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 100);
            rectTran.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 30);
            rectTran.anchoredPosition = Vector2.zero;
            Selection.activeGameObject = go;// 默认添加 附加组件
        }

        [MenuItem("GameObject/UI/To UIText")]
        public static void ChangetoUIText()
        {
            GameObject go = Selection.activeGameObject;
            if (!go) return;
            Text[] textComponents = go.GetComponentsInChildren<Text>();
            for (int i = 0; i < textComponents.Length; i++)
            {
                if (textComponents[i] is UIText) continue;
                string str = textComponents[i].text;
                Font font = textComponents[i].font;
                FontStyle fStyle = textComponents[i].fontStyle;
                int fSize = textComponents[i].fontSize;
                float lineSpacing = textComponents[i].lineSpacing;
                bool isRich = textComponents[i].supportRichText;
                TextAnchor anchor = textComponents[i].alignment;
                bool alignByGeomentry = textComponents[i].alignByGeometry;
                HorizontalWrapMode horizontalWrapMode = textComponents[i].horizontalOverflow;
                VerticalWrapMode verticalWrapMode = textComponents[i].verticalOverflow;
                bool bestFit = textComponents[i].resizeTextForBestFit;
                Color color = textComponents[i].color;
                Material mtr = textComponents[i].material;
                bool raycastTarget = textComponents[i].raycastTarget;

                GameObject itemObj = textComponents[i].gameObject;
                GameObject.DestroyImmediate(textComponents[i]);

                UIText t2 = itemObj.AddComponent<UIText>();
                t2.text = str;
                t2.font = font;
                t2.fontStyle = fStyle;
                t2.fontSize = fSize;
                t2.lineSpacing = lineSpacing;
                t2.supportRichText = isRich;
                t2.alignment = anchor;
                t2.alignByGeometry = alignByGeomentry;
                t2.horizontalOverflow = horizontalWrapMode;
                t2.verticalOverflow = verticalWrapMode;
                t2.resizeTextForBestFit = bestFit;
                t2.color = color;
                t2.material = mtr;
                t2.raycastTarget = raycastTarget;
                // t2.
            }
        }
        [MenuItem("GameObject/UI/To Text")]
        public static void ChangetoText()
        {
            GameObject go = Selection.activeGameObject;
            if (!go) return;
            UIText[] textComponents = go.GetComponentsInChildren<UIText>();
            for (int i = 0; i < textComponents.Length; i++)
            {
                if (textComponents[i].GetType().Equals(typeof(Text)))
                    continue;
                string str = textComponents[i].text;
                Font font = textComponents[i].font;
                FontStyle fStyle = textComponents[i].fontStyle;
                int fSize = textComponents[i].fontSize;
                float lineSpacing = textComponents[i].lineSpacing;
                bool isRich = textComponents[i].supportRichText;
                TextAnchor anchor = textComponents[i].alignment;
                bool alignByGeomentry = textComponents[i].alignByGeometry;
                HorizontalWrapMode horizontalWrapMode = textComponents[i].horizontalOverflow;
                VerticalWrapMode verticalWrapMode = textComponents[i].verticalOverflow;
                bool bestFit = textComponents[i].resizeTextForBestFit;
                Color color = textComponents[i].color;
                Material mtr = textComponents[i].material;
                bool raycastTarget = textComponents[i].raycastTarget;

                GameObject itemObj = textComponents[i].gameObject;
                GameObject.DestroyImmediate(textComponents[i]);

                Text t2 = itemObj.AddComponent<Text>();
                t2.text = str;
                t2.font = font;
                t2.fontStyle = fStyle;
                t2.fontSize = fSize;
                t2.lineSpacing = lineSpacing;
                t2.supportRichText = isRich;
                t2.alignment = anchor;
                t2.alignByGeometry = alignByGeomentry;
                t2.horizontalOverflow = horizontalWrapMode;
                t2.verticalOverflow = verticalWrapMode;
                t2.resizeTextForBestFit = bestFit;
                t2.color = color;
                t2.material = mtr;
                t2.raycastTarget = raycastTarget;
                // t2.
            }
        }

        [MenuItem("Tools/i18n/生成本地化最终文件(*.txt)")]
        public static void SerializeToFile()
        {
            i18n.SaveSerializedFile();
        }
    }
}
